// jQuery UI Datepicker localization
jQuery(function($){
	$.datepicker.regional['fr'] = {
		closeText: 'Fermer',
		prevText: '&#x3c;Préc',
		nextText: 'Suiv&#x3e;',
		currentText: 'Courant',
		monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
		'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
		monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
		'Jul','Aoû','Sep','Oct','Nov','Déc'],
		dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
		dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
		dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
		weekHeader: 'Sm',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''
	};
	$.datepicker.setDefaults($.datepicker.regional['fr']);
});

// HTML Encoding and Decoding
function htmlEncode(value) {
	return $('<div/>').text(value).html();
}

function htmlDecode(value) {
	return $('<div/>').html(value).text();
}

// Regular expressions
var rexp_mail = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/,
	rexp_date = /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/,
	rexp_hour = /^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/,
	rexp_password = /(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,15})$/,
	rexp_postal = /^((0[1-9])|([1-8][0-9])|(9[0-8])|(2A)|(2B))[0-9]{3}$/;

// Form checking utilities
function check_length(o, n, min, max) {
	if(o.val().length > max || o.val().length < min) {
		o.addClass('ui-state-error');
		alert('Merci de renseigner le champ \''+n+'\'.');
		return false;
	}
	return true;
}

function check_regexp(o, regexp, n) {
	if(!(regexp.test(o.val()))) {
		o.addClass('ui-state-error');
		alert(n);
		return false;
	}
	return true;
}

function check_dates(before, after, n) {
	if (before.datepicker('getDate') > after.datepicker('getDate')) {
		before.addClass('ui-state-error');
		after.addClass('ui-state-error');
		alert(n);
		return false;
	}
	return true;
}

// Credentials checking function
function check_credentials(o) {
	var res = 'no';
	$.ajax({
		type:	'POST',
		url:	'ajax/check_credentials.php',
		data:	'operation='+o,
		async:	false,
		success: function(msg){
			res = msg;
		}
	});
	return res;
}

// Loading functions
function showLoading() {
	$('div#loading-div').dialog({
		height: 200,
		width: 400,
		modal: true
	});
	$('div#progress').progressbar({ value: 0 });
}

function addLoading(unit) {
	$('div#progress').progressbar({
		value: $('div#progress').progressbar('value')+(unit)
	});
}

function closeLoading() {
	if ($('div#progress').progressbar('value') >= 100)
		$('div#loading-div').dialog('close');
}

// jQuery powered
$(document).ready(function(){

	// TinyMCE
	$('textarea').tinymce({
		script_url : 'js/editor/tiny_mce.js',
		theme : 'advanced',
		language: 'fr',
		plugins : 'advlink,advlist,autolink,bbcode,contextmenu,inlinepopups,insertdatetime,lists,nonbreaking,paste,preview,print,searchreplace,style,tabfocus,table',
		theme_advanced_buttons1 : 'newdocument,print,preview,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,|,cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent',
		theme_advanced_buttons2 : 'undo,redo,|,link,unlink,code,|,insertdate,inserttime,|,tablecontrols,|,hr,removeformat,|,sub,sup,|,charmap,blockquote',
		theme_advanced_buttons3 : '',
		theme_advanced_toolbar_location : 'top',
		theme_advanced_toolbar_align : 'left',
	});
	
	// jQuery UI styles
	$('a.nav').each(function(index){
		if (index%3 == 0)
			$(this).button({ icons: { primary: 'ui-icon-gear' } });
		if (index%3 == 1)
			$(this).button({ icons: { primary: 'ui-icon-plus' } });
		if (index%3 == 2)
			$(this).button({ icons: { primary: 'ui-icon-trash' } });
	});
	$('a.submit').button({ icons: { primary: 'ui-icon-disk' } });
	$('a.merge').button({ icons: { primary: 'ui-icon-shuffle' } });
	$('a.upload').button({ icons: { primary: 'ui-icon-transferthick-e-w' } });
	$('a.new').button({ icons: { primary: 'ui-icon-plus' } });
	$('a.email').button({ icons: { primary: 'ui-icon-mail-closed' } });
	$('a.search').button({ icons: { primary: 'ui-icon-search' } });
	$('a.selectall').button({ icons: { primary: 'ui-icon-refresh' } });
	$('a.selectnone').button({ icons: { primary: 'ui-icon-cancel' } });
	$('a.delete-doc').button();
	$('a#logout').button({ icons: { primary: 'ui-icon-power' } });
	
	// Select All event
	$('a.selectall').click(function(){
		$('table.table-objects input:checkbox').not(':checked').click();
	});
	
	// Select None event
	$('a.selectnone').click(function(){
		$('table.table-objects input:checkbox:checked').click();
	});
	
	// jQuery UI Datepicker default options
	$.datepicker.setDefaults({
		changeYear: true,
		showButtonPanel: true,
		showWeek: true,
		firstDay: 1,
		numberOfMonths: 2
	});
	$.datepicker.setDefaults($.datepicker.regional['fr']);
	
	// Login functions
	$('a#form-login').click(function(){
		
		// Getting inputs
		var login = $('input[name=login-user]'),
			password = $('input[name=login-password]'),
			allFields = $([]).add(login).add(password);
		
		// Checking form validity
		allFields.removeClass('ui-state-error');
		var valid = true;
		valid = valid && check_length(login, 'Utilisateur', 1, 255);
		valid = valid && check_regexp(password, rexp_password, 'Le mot de passe doit contenir au moins une lettre, un chiffre et doit contenir entre 8 et 15 caractères');
		
		// We have errors
		if (!valid)
			return false;

		// No error: AJAX processing
		$.ajax({
			type:	'POST',
			url:	'process/crmuser_login.php',
			data:	'login='+login.val()+'&password='+password.val(),
			success: function(msg){
				if (msg == 'OK')
					location.reload();
				else
					alert(msg);
			}
		});
		return false;
	});
	
	// Logout function
	$('a#logout').click(function(){
		$.ajax({
			type:	'POST',
			url:	'process/crmuser_logout.php',
			success: function(){
				location.reload();
			}
		});
		return false;
	});
	
	// Search field
	$('a#search').click(function(){
		$('input#search-field').addClass('loading');
		$.ajax({
			type:	'POST',
			url:	'ajax/put_searchfield.php',
			data:	'item='+$(this).attr('href')+'&value='+$('input#search-field').val(),
			success: function(){
				location.reload();
			}
		});
		return false;
	});
	
	// Menu links
	$('a#activities-by-crmuser').click(function(){
		var e = $(this);
		e.addClass('loading');
		$.ajax({
			type:	'POST',
			url:	'ajax/load_crmusers.php',
			data:	'id=-1',
			success: function(msg) {
				var select = $('div#menu_select');
				e.removeClass('loading');
				select.html(msg);
				select.dialog({
					resizable: true,
					height: 500,
					width: 500,
					modal: true,
					buttons: {
						'Sélectionner': function(){
							var checked = $('input:radio:checked');
							if (checked.length >= 0) {
								$(this).dialog('close');
								showLoading();
								addLoading(100);
								$(location).attr('href', 'activities.php?sep='+checked.first().val());
							}
						},
						'Annuler': function(){
							$(this).dialog('close');
						}
					}
				});
			}
		});
	});
	
	$('a#contacts-by-company').click(function(){
		var e = $(this);
		e.addClass('loading');
		$.ajax({
			type:	'POST',
			url:	'ajax/load_companies.php',
			data:	'id=-1',
			success: function(msg) {
				var select = $('div#menu_select');
				e.removeClass('loading');
				select.html(msg);
				select.dialog({
					resizable: true,
					height: 500,
					width: 500,
					modal: true,
					buttons: {
						'Sélectionner': function(){
							var checked = $('input:radio:checked');
							if (checked.length >= 0) {
								$(this).dialog('close');
								showLoading();
								addLoading(100);
								$(location).attr('href', 'contacts.php?sep='+checked.first().val());
							}
						},
						'Annuler': function(){
							$(this).dialog('close');
						}
					}
				});
			}
		});
	});
	
	$('a#companies-by-sector').click(function(){
		var e = $(this);
		e.addClass('loading');
		$.ajax({
			type:	'POST',
			url:	'ajax/load_sectors.php',
			data:	'id=-1',
			success: function(msg) {
				var select = $('div#menu_select');
				e.removeClass('loading');
				select.html(msg);
				select.dialog({
					resizable: true,
					height: 500,
					width: 500,
					modal: true,
					buttons: {
						'Sélectionner': function(){
							var checked = $('input:radio:checked');
							if (checked.length >= 0) {
								$(this).dialog('close');
								showLoading();
								addLoading(100);
								$(location).attr('href', 'companies.php?sep='+checked.first().val());
							}
						},
						'Annuler': function(){
							$(this).dialog('close');
						}
					}
				});
			}
		});
	});
	
	$('a#supportcases-by-crmuser').click(function(){
		var e = $(this);
		e.addClass('loading');
		$.ajax({
			type:	'POST',
			url:	'ajax/load_crmusers.php',
			data:	'id=-1',
			success: function(msg) {
				var select = $('div#menu_select');
				e.removeClass('loading');
				select.html(msg);
				select.dialog({
					resizable: true,
					height: 500,
					width: 500,
					modal: true,
					buttons: {
						'Sélectionner': function(){
							var checked = $('input:radio:checked');
							if (checked.length >= 0) {
								$(this).dialog('close');
								showLoading();
								addLoading(100);
								$(location).attr('href', 'supportcases.php?sep='+checked.first().val());
							}
						},
						'Annuler': function(){
							$(this).dialog('close');
						}
					}
				});
			}
		});
	});
});